package com.hxy.platform.admin.controller;

import com.hxy.platform.admin.common.ServerResponse;
import com.hxy.platform.admin.pojo.Product;
import com.hxy.platform.admin.service.FileService;
import com.hxy.platform.admin.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private FileService fileService;

    /**
     * 获取所有产品
     * @param modelMap
     * @return
     */
    @RequestMapping("product/getAll")
    public String getAllProduct(ModelMap modelMap) {
        List<Product> productList = productService.getAll();
        modelMap.addAttribute("productList",productList);
        return "product";
    }
    /**
     * 添加产品
     */
    @RequestMapping("product/addProduct")
    public String addProduct(ModelMap modelMap, Product product,HttpServletRequest request) {
        if (StringUtils.isBlank(product.getTitle())) {
            return "addProduct";
        }

        int result = productService.addProduct(product);
        if (result > 0) {
            List<Product> productList = productService.getAll();
            modelMap.addAttribute("productList",productList);
            return "product";
        }
        return null;
    }

    /**
     * 删除产品
     */
    @RequestMapping("user/deleteProduct")
    public String deleteProductById(@RequestParam("id") Integer id, ModelMap modelMap) {
        int result = productService.deleteProductById(id);
        if (result > 0) {
            List<Product> productList = productService.getAll();
            modelMap.addAttribute("productList",productList);
            return "product";
        }
        return null;
    }

    /**
     * 图片上传
     */
    @RequestMapping("image/upload")
    @ResponseBody
    public ServerResponse upload(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String upload = fileService.upload(file, path);
        return ServerResponse.createBySuccess("上传成功", upload);
    }

}
